//
//  BRCardNumView.m
//  Kexu
//
//  Created by IOS on 2023/7/22.
//

#import "BRCardNumView.h"

@interface BRCardNumView ()<QMUITextFieldDelegate>

@end

@implementation BRCardNumView

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUI];
    }
    return self;
}

- (void)setDateErro:(BOOL)dateErro {
    _dateErro = dateErro;
    
    self.cardDateTF.textColor = dateErro ? UIColorRed : kColorTitle;
}

- (void)setCardNumErro:(BOOL)cardNumErro {
    _cardNumErro = cardNumErro;
    
    self.cardNumTF.textColor = cardNumErro ? UIColorRed : kColorTitle;
}

#pragma mark - TextField Delegate --
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason {
    
    NSLog(@"textFieldDidEndEditing = %@",textField.text);
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    NSLog(@"textFieldShouldEndEditing = %@",textField.text);
    
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    NSLog(@"textFieldShouldBeginEditing = %@",textField.text);
    
    return YES;
}

- (void)textFieldDidChangeSelection:(UITextField *)textField {
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if ([string isEqualToString:@""]) {
        if (textField == self.cardNumTF)  self.cardNumErro = NO;
        if (textField == self.cardDateTF)  self.dateErro = NO;
        return YES;
    }
    if (textField == self.cardNumTF) {
        if (self.cardNumErro) return NO;
        NSString *text = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (text.length != 0 && text.length %4 == 0) {
            
            textField.text = [NSString stringWithFormat:@"%@ ",textField.text];
        }
        
        NSString *new = [NSString stringWithFormat:@"%@%@",textField.text,string];
        if (new.length == 19) {
            new = [new stringByReplacingOccurrencesOfString:@" " withString:@""];
            
            //校验卡号规则
            BOOL isV = [STPCardValidator validationStateForNumber:new validatingCardBrand:YES];
            if (isV) {
                self.cardNumErro = YES;
            }
        }
        
        return YES;
    }
    if (textField == self.cardDateTF) {
        if (self.dateErro) return NO;
        NSLog(@"%@-",textField.text);
        textField.textColor = kColorTitle;
        
        NSString *new = [NSString stringWithFormat:@"%@%@",textField.text,string];
        if (new.length == 1) {
            if (new.integerValue > 1) {
                new = [NSString stringWithFormat:@"0%@/",new];
                _cardDateTF.text = new;
                return NO;
            }
        }
        if (new.length == 2) {
            if (new.integerValue > 0 && new.integerValue <= 12) {
                new = [NSString stringWithFormat:@"%@/",new];
                _cardDateTF.text = new;
                return NO;
            }
            self.dateErro = YES;
        }
        if (new.length == 5) {
            // 校验是否小于当前时间
            BOOL isGreat = [self br_timeComparition:new];
            if (!isGreat) {
                self.dateErro = YES;
            }
        }

        if (textField.text.length == 2) {
            new = [NSString stringWithFormat:@"%@/",textField.text];
            _cardDateTF.text = new;
//            return YES;
        }
        return YES;
    }
    return YES;
}

- (void)valueChange:(QMUITextField *)textField {
    
}


- (BOOL)br_timeComparition:(NSString *)time {
    
    // 获取当前日期和时间
    NSDate *currentDate = [NSDate date];

    // 获取当前年份和月份的组件
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *currentComponents = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth fromDate:currentDate];
    NSInteger currentYear = [currentComponents year] - 2000; // 获取到的年份为四位数，需要减去 2000
    NSInteger currentMonth = [currentComponents month];

    // 解析给定日期字符串，获取年份和月份的组件
    NSString *dateString = time;
    NSArray *components = [dateString componentsSeparatedByString:@"/"];
    NSInteger givenMonth = [[components objectAtIndex:0] integerValue];
    NSInteger givenYear = [[components objectAtIndex:1] integerValue];

    // 比较给定日期和当前日期
    if (givenYear < currentYear || (givenYear == currentYear && givenMonth < currentMonth)) {
        NSLog(@"给定日期早于当前日期");
    } else if (givenYear == currentYear && givenMonth == currentMonth) {
        NSLog(@"给定日期与当前日期相同");
    } else {
        NSLog(@"给定日期晚于当前日期");
        return YES;
    }
    return NO;
}



#pragma mark - UI --
- (void)setUI {
    
    self.backgroundColor = UIColor.whiteColor;
    
    [self addSubview:self.cardNumTF];
    [self addSubview:self.cardDateTF];
    [self addSubview:self.cardCVCTF];
    
    QMUILabel *titleL = [BRToolsView br_label:Localized(@"wallet_cardNum") textColor:kColorTitle font:[UIFont fontS:14]];
    QMUILabel *dateL = [BRToolsView br_label:Localized(@"wallet_expiryDate") textColor:kColorTitle font:[UIFont fontS:14]];
    QMUILabel *cvcL = [BRToolsView br_label:@"CVC" textColor:kColorTitle font:[UIFont fontS:14]];
    
    [self addSubview:titleL];
    [self addSubview:dateL];
    [self addSubview:cvcL];
    
    [self.cardNumTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.left.offset(0);
        make.right.offset(0);
        make.top.equalTo(titleL.mas_bottom).offset(10);
    }];
    
    UIStackView *stack = [[UIStackView alloc] init];
    stack.spacing = 10;
    stack.distribution = UIStackViewDistributionFillEqually;
    [self addSubview:stack];
    [stack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(52);
        make.left.offset(0);
        make.right.offset(0);
        make.top.equalTo(self.cardNumTF.mas_bottom).offset(40);
        make.bottom.offset(0);
    }];
    
    [stack addArrangedSubview:self.cardDateTF];
    [stack addArrangedSubview:self.cardCVCTF];
    
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.top.offset(0);
    }];
    [dateL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(10);
        make.bottom.equalTo(stack.mas_top).offset(-10);
    }];
    [cvcL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.cardCVCTF.mas_left).offset(10);
        make.bottom.equalTo(stack.mas_top).offset(-10);
    }];
    
}

- (QMUITextField *)cardNumTF {
    
    if (_cardNumTF == nil) {
        _cardNumTF = [[QMUITextField alloc] init];
        
        _cardNumTF.textInsets = UIEdgeInsetsMake(0, 20, 0, 20);
        _cardNumTF.placeholderColor = UIColorMakeWithHex(@"#AAAAAC");
        _cardNumTF.font = [UIFont fontM:14];
        _cardNumTF.textColor = kColorTitle;
        _cardNumTF.tintColor = kColorMain;
        _cardNumTF.placeholder = @"4242 4242 4242 4242";
        _cardNumTF.delegate = self;
        _cardNumTF.layer.cornerRadius = 10;
        _cardNumTF.backgroundColor = kColorBGF5;
        _cardNumTF.maximumTextLength = 19;
        _cardNumTF.keyboardType = UIKeyboardTypeNamePhonePad;
        [_cardNumTF addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    }
    return _cardNumTF;
}

- (QMUITextField *)cardDateTF {
    if (_cardDateTF == nil) {
        _cardDateTF = [[QMUITextField alloc] init];
        
        _cardDateTF.textInsets = UIEdgeInsetsMake(0, 20, 0, 20);
        _cardDateTF.placeholderColor = UIColorMakeWithHex(@"#AAAAAC");
        _cardDateTF.font = [UIFont fontM:14];
        _cardDateTF.textColor = kColorTitle;
        _cardDateTF.tintColor = kColorMain;
        _cardDateTF.placeholder = Localized(@"wallet_stripeMMYY");
        _cardDateTF.delegate = self;
        _cardDateTF.layer.cornerRadius = 10;
        _cardDateTF.backgroundColor = kColorBGF5;
        _cardDateTF.maximumTextLength = 5;
        _cardDateTF.keyboardType = UIKeyboardTypeNamePhonePad;
        [_cardDateTF addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    }
    return _cardDateTF;
}

- (QMUITextField *)cardCVCTF {
    if (_cardCVCTF == nil) {
        _cardCVCTF = [[QMUITextField alloc] init];
        
        _cardCVCTF.textInsets = UIEdgeInsetsMake(0, 20, 0, 20);
        _cardCVCTF.placeholderColor = UIColorMakeWithHex(@"#AAAAAC");
        _cardCVCTF.font = [UIFont fontM:14];
        _cardCVCTF.textColor = kColorTitle;
        _cardCVCTF.tintColor = kColorMain;
        _cardCVCTF.placeholder = @"CVC";
        _cardCVCTF.delegate = self;
        _cardCVCTF.layer.cornerRadius = 10;
        _cardCVCTF.backgroundColor = kColorBGF5;
        _cardCVCTF.maximumTextLength = 4;
        _cardCVCTF.keyboardType = UIKeyboardTypeNamePhonePad;
        [_cardCVCTF addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    }
    return _cardCVCTF;
}

@end
